﻿using System.Linq;
using System.ServiceModel.Security;
using System.Web.Http;
using Enferno.Public.Web.Components.Server.ExceptionFilters;
using Enferno.Public.Web.Components.Server.Managers;
using Enferno.Public.Web.Components.Server.ViewModels;
using Enferno.StormApiClient.Customers;

namespace Enferno.Public.Web.Components.Server.Controllers
{
    [RoutePrefix("api/account")]
    [ServiceModelFaultExceptionFilter]
    public class AccountController : ApiController
    {
        private readonly CustomerManager _customerManager;

        public AccountController()
        {
            _customerManager = new CustomerManager();
        }

        [Route("login")]
        [HttpPost]
        public CustomerViewModel Login(LoginModel model)
        {
            return _customerManager.Login(model.UserName, model.Password, model.RememberMe);
        }

        [Route("logout")]
        [HttpPost]
        public void Logout()
        {
            _customerManager.Logout();
        }

        [Route("getpersoninfo")]
        [HttpGet]
        public AddressAndPersonInformationViewModel GetPersonInformation(string socialSecurityNumber)
        {
            var customer = _customerManager.GetCustomerInformation(socialSecurityNumber);
            var viewModel = new AddressAndPersonInformationViewModel
            {
                Address = customer.InvoiceAddress,
                PersonInformation = customer.Person
            };
            return viewModel;
        }

        [Route("getcompanyinfo")]
        [HttpGet]
        public AddressAndCompanyInformationViewModel GetCompanyInformation(string organisationNumber)
        {
            var customer = _customerManager.GetCustomerInformation(organisationNumber);
            if(!customer.Companies.Any())
                return new AddressAndCompanyInformationViewModel();
            var viewModel = new AddressAndCompanyInformationViewModel
            {
                CompanyInformation = customer.Companies.ToList()[0].CompanyInformation,
                Address = customer.Companies.ToList()[0].InvoiceAddress
            };
            return viewModel;
        }
    }

    public class AddressAndPersonInformationViewModel
    {
        public PersonInformationViewModel PersonInformation { get; set; }
        public AddressViewModel Address { get; set; }
    }

    public class AddressAndCompanyInformationViewModel
    {
        public CompanyInformationViewModel CompanyInformation { get; set; }
        public AddressViewModel Address { get; set; }
    }

    public class LoginModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }
}
